
const port = process.env.PORT || 8080
const env = process.env.NODE_ENV
const Koa = require('koa')
const serve = require('koa-static')
const config = require('config')

const cluster = require('cluster')
const OS = require('os')
const numCPUs = OS.cpus().length
const middleware = require('./middleware')
const log = require('./libs/logger')

if (cluster.isMaster && config.isCluseter) {
  // log.info(`主进程 ${process.pid} 正在运行`)

  // 衍生工作进程。
  for (let i = 0; i < numCPUs; i++) {
    cluster.fork()
  }

  cluster.on('exit', (worker, code, signal) => {
    log.warn(`工作进程 ${worker.process.pid} 已退出`)
  })
} else {
  const app = new Koa()

  // 初始化log，跟踪所有请求和response
  log.init(app)

  middleware(app)

  app.on('error', (error, ctx) => {
    // log.error('server error:', error)
    console.log('server error:', error)
  })

  if (env === 'production') {
    // 线上
    const http = require('http')
    http.createServer(app.callback()).listen(port)
  } else {
    // 本地
    app.use(serve('./public'))
    const http = require('http')
    http.createServer(app.callback()).listen(port)
  }

  log.info('app listening on port:' + port)
  console.log('app listening on port:', port)
}
